"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 数据库系统
Case Name   : 一主两备，反复进行主备切换再重建
Create At   : 2020/07/27
@zou_jialiang0505328126
Description :
    1.备节点重建
    2.查询集群状态
    3.备节点A升主
    4.重启集群
    5.原主节点（现备节点A）重建
    6.重启集群
    7.备节点B升主
    8.重启集群
    9.原备节点A重建
    10.查询集群状态
    11.在主节点执行
    12.备节点查询
Expect      :    
History     :
"""


import unittest
import time
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from yat.test import Node

logger = Logger()
common = Common()
commonshpri = CommonSH('PrimaryDbUser')
commonshsta1 = CommonSH('Standby1DbUser')
commonshsta2 = CommonSH('Standby2DbUser')


class BuildRepeat(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        logger.info("-----------this is setup-----------")
        self.constant = Constant()
        self.tbname = 'test_table55'
        logger.info('-------Opengauss_Reliability_Dbsys_Case139.py start---')

    def test_build_repeat(self):
        logger.info("-----------build standby1 -----------")
        build_msg = commonshsta1.buildStandby()
        logger.info(build_msg)
        self.assertIn(self.constant.BUILD_SUCCESS_MSG, build_msg)

        logger.info("-----------check opengauss status-----------")
        result = commonshpri.getDbClusterStatus("status")
        self.assertTrue(result)

        logger.info("-----------switchover standby1(P)-----------")
        result = commonshsta1.executeGsctl(
            'switchover', self.constant.SWITCHOVER_SUCCESS_MSG)
        self.assertTrue(result)
        result = commonshsta1.exec_refresh_conf()
        self.assertTrue(result)

        logger.info("-----------restart cluster-----------")
        stopres = commonshsta1.stopDbCluster()
        self.assertTrue(stopres)
        startres = commonshsta1.startDbCluster()
        self.assertTrue(startres)

        logger.info("-----------build primary(S) -----------")
        build_msg = commonshpri.buildStandby()
        logger.info(build_msg)
        self.assertIn(self.constant.BUILD_SUCCESS_MSG, build_msg)

        logger.info("-----------restart cluster-----------")
        stopres = commonshsta1.stopDbCluster()
        self.assertTrue(stopres)
        startres = commonshsta1.startDbCluster()
        self.assertTrue(startres)

        logger.info("-----------check opengauss status-----------")
        result = commonshpri.getDbClusterStatus("status")
        self.assertTrue(result)

        logger.info("-----------switchover standby2(P)-----------")
        result = commonshsta2.executeGsctl(
            'switchover', self.constant.SWITCHOVER_SUCCESS_MSG)
        self.assertTrue(result)
        result = commonshsta2.exec_refresh_conf()
        self.assertTrue(result)

        logger.info("-----------restart cluster-----------")
        stopres = commonshsta1.stopDbCluster()
        self.assertTrue(stopres)
        startres = commonshsta1.startDbCluster()
        self.assertTrue(startres)

        logger.info("-----------build standby1(S) -----------")
        build_msg = commonshsta1.buildStandby()
        logger.info(build_msg)
        self.assertIn(self.constant.BUILD_SUCCESS_MSG, build_msg)
        time.sleep(50)

        logger.info("-----------check opengauss status-----------")
        result = commonshpri.getDbClusterStatus("status")
        self.assertTrue(result)

        logger.info("------standby2(P)create table &insert data------")
        sql = f"create table {self.tbname}(id int,name varchar(20));" \
            f" insert into {self.tbname} values(1,'aaa'),(1,'aaa');"
        create_msg = commonshsta2.executDbSql(sql)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, create_msg)

        logger.info("-----------check data consistency-----------")
        flag = commonshsta1.check_data_consistency()
        self.assertTrue(flag)
        logger.info("-----------query data consistency-----------")
        sql = f"select count(*) from {self.tbname};"
        result = commonshsta1.executDbSql(sql)
        logger.info(result)
        self.assertIn('2', result)
        result = commonshsta1.executDbSql(sql)
        logger.info(result)
        self.assertIn('2', result)

    def tearDown(self):
        logger.info('----------------this is tearDown---------------')
        logger.info("-----------drop table -----------")
        result = commonshsta2.executDbSql(f'drop table {self.tbname};')
        logger.info(result)

        self.pri_root = Node(node='PrimaryRoot')
        host_name = self.pri_root.sh('hostname').result()
        if commonshpri.check_whether_need_switch(host_name):
            logger.info('----switchover----')
            if commonshpri.check_whether_need_build():
                commonshpri.executeGsctl('build',
                                         self.constant.REBUILD_SUCCESS_MSG)
            logger.info('---switchover---')
            success_msg = self.constant.SWITCHOVER_SUCCESS_MSG
            result = commonshpri.executeGsctl('switchover', success_msg)
            logger.info(result)
            result = commonshpri.exec_refresh_conf()
            logger.info(result)